package park.job;

import com.google.gson.Gson;

import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import park.record.CenterTradingRecord;
import park.record.ConfirmEntryRecord;
import park.record.EntryRecord;

import java.util.HashMap;

public class TaskEnterJob implements Job {
	private static Logger logger = Logger.getLogger(TaskEnterJob.class);

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		Long timeMark = System.currentTimeMillis(); // timemark

		String jobId;
		logger.info("starting entryJob: " + (jobId = context.getJobDetail().getKey().getName()) + " at time mark:"
				+ timeMark);

		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		EntryRecord entry = (EntryRecord) jobDataMap.get("entryRecord");

		entry.setEnterTime(System.currentTimeMillis() - 1000 * 60 * 10);

		ParkInterfaceCollection pc = ParkInterfaceCollection.getInstance();

		
		try {

			String rsCheckFree = pc.postFunc("checkFreeVehicle", entry);
			logger.info("job:" + jobId + "|  checkFreeVehicle response " + (System.currentTimeMillis() - timeMark)
					+ " ms after time mark");
			logger.info("job:" + jobId + "|  response of checkFreeVehicle is : " + rsCheckFree.toString());

			checkResponse("checkFreeVehicle", rsCheckFree, "rtnCode");
			String rsSaveEntry = pc.postFunc("saveEntryRecord", entry);
			logger.info("job:" + jobId + "|  saveEntryRecord response " + (System.currentTimeMillis() - timeMark)
					+ " ms after time mark");
			logger.info("job:" + jobId + "|  response of saveEntryRecord is : " + rsSaveEntry.toString());

			ConfirmEntryRecord confirm = getConfirmRecord(entry, rsSaveEntry);
			checkResponse("saveEntryRecord", rsSaveEntry, "newPk");

			String rsConfirmEntry = pc.postFunc("confirmEntryRecord", confirm);
			logger.info("job:" + jobId + "|  confirmEntryRecord response " + (System.currentTimeMillis() - timeMark)
					+ " ms after time mark");
			logger.info("job:" + jobId + "|  response of confirmEntryRecord is : " + rsConfirmEntry.toString());
			checkResponse("confirmEntryRecord", rsConfirmEntry, "null");
		} catch (Exception e) {
			logger.warn("job:" + jobId + "| caught exception", e);
		}
	}

	private ConfirmEntryRecord getConfirmRecord(EntryRecord entry, String rsCheckFree) {
		Gson gson = new Gson();
		HashMap<String, Double> re = gson.fromJson(rsCheckFree, HashMap.class);
		int entryRecordId = new Double(re.get("newPk")).intValue();

		ConfirmEntryRecord confirm = new ConfirmEntryRecord();
		CenterTradingRecord center = new CenterTradingRecord();
		center.setEntryId(entry.getEntryId());
		center.setEntryPhoto("");
		center.setEnterTime(entry.getEnterTime());
		center.setEntryTime(entry.getEnterTime());
		center.setParkId(Integer.parseInt(entry.getEntryId() + 10));
		center.setPlateNo(entry.getPlateNo());
		center.setPlateParseInfo("");
		center.setTradeType("");
		center.setVehicleType(entry.getVehicleType());
		center.setTerminalId(entry.getTerminalId());
		center.setTollCollectorName(entry.getTollCollectorName());

		confirm.setCenterTradingRecord(center);
		confirm.setEntryId(entry.getEntryId());
		confirm.setEntryRecordId(entryRecordId);
		confirm.setPlateNo(entry.getPlateNo());
		confirm.setTerminalId(entry.getTerminalId());
		confirm.setTollCollectorName(entry.getTollCollectorName());
		confirm.setVehicleType(entry.getVehicleType());
		return confirm;
	}

	private void checkResponse(String url, String res, String key) {
		if (!res.contains(key)) {
			logger.error("!!!!res of " + res + " has no key of " + key);
			// String[] columns = new String[]{"aa","bb","cc"};
			// ExcelOpr excel = new ExcelOpr(url + "Error");
			// int count = excel.getWorkbook().getSheet("First
			// Sheet").getRows();
			//
			// excel.addCell(count, url, res, "!!!!res of " + res + " has no key
			// of " + key);
			// excel.writeAndCancle();

		} else {
			logger.info("res: " + res + " has key : " + key);
		}

	}

}
